package model

import (
	"database/sql"
	"errors"
	"github.com/jmoiron/sqlx"
	"time"
	"zimuzu_cvn_web_api/config"
	. "zimuzu_cvn_web_api/pkg/e"
	"zimuzu_cvn_web_api/pkg/errno"
)

//首页轮播图模块ID
const WebAnnouncementCate = 10
const AppAnnouncementCate = 11

type Announcement struct {
	ID         int    `db:"id" json:"id,omitempty"`
	Title      string `db:"title" json:"title,omitempty"`
	Url        string `db:"url" json:"url,omitempty"`
	UpdateTime string `db:"dateline" json:"dateline,omitempty"`
	Content    string `db:"content" json:"content,omitempty"`
}

type AnnouncementCategory struct {
	ID   int    `db:"id" json:"id" form:"id"`
	Name string `db:"name" json:"name" form:"name" binding:"required"`
}

//查询web公告列表
//Auth: Xu
func GetWebAnnouncement(db sqlx.Queryer, page int, per int) ([]Announcement, error) {
	res := make([]Announcement, 0)
	start := (page - 1) * per
	err := sqlx.Select(db, &res, "select id, title,url,from_unixtime(dateline, '%Y-%m-%d') dateline from announcement where category = ?  order by dateline desc limit ?,? ", WebAnnouncementCate, start, per)
	if err != nil {
		Log("info", "公告查询失败！", err.Error())
		return res, err
	}

	return res, nil
}

//查询app公告列表
//Auth: Xu
func GetAppAnnouncement(db sqlx.Queryer, page int, per int) ([]Announcement, error) {
	res := make([]Announcement, 0)
	start := (page - 1) * per
	err := sqlx.Select(db, &res, "select id, title,url,from_unixtime(dateline, '%Y-%m-%d') dateline from announcement where category = ?  order by dateline desc limit ?,? ", AppAnnouncementCate, start, per)
	if err == sql.ErrNoRows {
		err = nil
	}
	if err != nil {
		Log("info", "公告查询失败！", err.Error())
		return res, err
	}

	return res, nil
}

//查询app公告数
//Auth: Xu
func GetAppAnnouncementNum(db sqlx.Queryer) (int, error) {
	var num int
	err := sqlx.Get(db, &num, "select count(*) from announcement where category = ? ", AppAnnouncementCate)
	if err == sql.ErrNoRows {
		err = nil
	}
	if err != nil {
		Log("info", "公告查询失败！", err.Error())
		return num, err
	}

	return num, nil
}

//查询app公告列表
//Auth: Xu
func GetAppAnnouncementDetail(db sqlx.Queryer, id int) (res Announcement, err error) {
	err = sqlx.Get(db, &res, "select title,from_unixtime(dateline, '%Y-%m-%d') dateline, content from announcement where id = ? ", id)
	if err == sql.ErrNoRows {
		err = nil
	}
	if err != nil {
		Log("info", "公告查询失败！", err.Error())
		return res, err
	}

	return res, nil
}

func GetAnnouncementCategoryList() (res []AnnouncementCategory, err error) {
	err = sqlx.Select(config.C.DB.DB, &res, "select id, name from announce_category order by id")
	if err != nil {
		Log("err", "查询公告分类失败！", err.Error())
		return
	}

	return
}

func AddNewAnnouncementCategory(name string) (err error) {
	res := sqlx.MustExec(config.C.DB.DB, "INSERT INTO announce_category SET name = ?", name)
	_, err = res.LastInsertId()
	if err != nil {
		Log("err", "新增公告分类失败！", err.Error())
		return errno.DbError
	}

	return nil
}

func UpdateNewAnnouncementCategory(id int, name string) (err error) {
	if id <= 0 {
		return errors.New("id 不能为空")
	}
	res := sqlx.MustExec(config.C.DB.DB, "UPDATE announce_category SET name = ? WHERE id = ?", name, id)
	_, err = res.RowsAffected()
	if err != nil {
		Log("err", "更新公告分类失败！", err.Error())
		return errno.DbError
	}

	return nil
}

func DeleteAnnouncementCategory(id int) (err error) {
	res := sqlx.MustExec(config.C.DB.DB, "DELETE FROM announce_category WHERE id = ?", id)
	_, err = res.RowsAffected()
	if err != nil {
		Log("err", err.Error())
		return
	}
	return
}

type AnnouncementAdmin struct {
	ID        int    `db:"id" json:"id" form:"id"`
	Title     string `db:"title" json:"title" form:"title" binding:"required"`
	Url       string `db:"url" json:"url" form:"url"`
	Category  int    `db:"category" json:"category" form:"category"`
	Recommend int    `db:"recommend" json:"recommend" form:"recommend"`
	Content   string `db:"content" json:"content" form:"content" binding:"required"`
	Dateline  string `db:"dateline" json:"dateline"`
}

func GetALLAnnouncementList(pageParams PageParams) (res []AnnouncementAdmin, err error) {
	start := (pageParams.Page - 1) * pageParams.Per
	err = sqlx.Select(config.C.DB.DB, &res, "select id, title, url, category, recommend, content, "+
		"from_unixtime(dateline, '%Y-%m-%d %H:%i:%s') dateline from announcement order by id DESC LIMIT ?, ?", start, pageParams.Per)
	if err != nil {
		Log("err", "查询公告列表失败！", err.Error())
		return
	}

	return
}

func UpdateAnnouncement(params AnnouncementAdmin) (err error) {
	if params.ID <= 0 {
		return errors.New("id 不能为空")
	}
	if len(params.Url) == 0 {
		params.Url = ""
	}
	res := sqlx.MustExec(config.C.DB.DB, "UPDATE announcement SET title = ?, url = ?, category = ?, recommend = ?, content = ?, updatetime = ? WHERE id = ?",
		params.Title, params.Url, params.Category, params.Recommend, params.Content, time.Now().Unix(), params.ID)
	_, err = res.RowsAffected()
	if err != nil {
		Log("err", "更新公告失败！", err.Error())
		return errno.DbError
	}

	return nil
}

func AddNewAnnouncement(params AnnouncementAdmin) (err error) {
	if len(params.Url) == 0 {
		params.Url = ""
	}
	res := sqlx.MustExec(config.C.DB.DB, "INSERT INTO announcement SET title = ?, url = ?, category = ?, recommend = ?, content = ?, dateline = ?",
		params.Title, params.Url, params.Category, params.Recommend, params.Content, time.Now().Unix())
	_, err = res.RowsAffected()
	if err != nil {
		Log("err", "新增公告失败！", err.Error())
		return errno.DbError
	}

	return nil
}

func DeleteAnnouncement(id int) (err error) {
	res := sqlx.MustExec(config.C.DB.DB, "DELETE FROM announcement WHERE id = ?", id)
	_, err = res.RowsAffected()
	if err != nil {
		Log("err", err.Error())
		return
	}
	return
}

func RecommendAnnouncement(id int) (err error) {
	res := sqlx.MustExec(config.C.DB.DB, "UPDATE announcement SET recommend = IF(recommend = 0, 1, 0) WHERE id = ?", id)
	_, err = res.RowsAffected()
	if err != nil {
		Log("err", err.Error())
		return
	}
	return
}
